package com.my.mycommonredis.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.TimeUnit;
@RequiredArgsConstructor
@Slf4j
public class RedissonLockService {


    @Autowired
    private final RedissonClient redissonClient;

    public RLock acquire(String lockKey,long expire){
        try {
            final RLock lockInstance = redissonClient.getLock(lockKey);
            lockInstance.lock(expire, TimeUnit.MILLISECONDS);
            return lockInstance;
        } catch (Exception e) {
            return null;
        }

    }
    /**
     * 释放锁。注意：必须和获取锁在一个线程中
     *
     * @param lockInstance 锁的实例，acquire返回的
     * @return 释放成功返回true，否则返回false
     */
    public boolean releaseLock(RLock lockInstance) {
        //用于检查当前线程是否持有该锁
        if (lockInstance.isHeldByCurrentThread()) {
            lockInstance.unlock();
            return true;
        }
        return false;
    }
}
